/* eslint-disable indent */
'use strict'
const path = require('path')
const defaultSettings = require('./src/settings')
// eslint-disable-next-line no-unused-vars
// const mock = require('./mock/mock-server.js')
// const FileListPlugin = require('./redevelop/plugin')
function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || 'Admin' // page title

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following method:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 9528 // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
/**
 * @type {import('@vue/cli-service').ProjectOptions}
 */
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  // publicPath: '/dist/',
  publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    // host: 'www.damddos.com',
    port: port,
    open: true,
    disableHostCheck: true,
    overlay: {
      warnings: false,
      errors: true
    },
    /**
     * @description set proxy fetch remote data or mock data from localhost.
     * if you set before, the date default fetch localhost. else proxy
     * *** 现在总体的思路是我们为接口默认提供五类服务可选择切换：yapi，mockoon, 本地mock, 后端开发，开发环境
     * *** 针对如下配置，有几个关键分法路径：
     * mocksign： 代理到对应的yapi服务中
     * anyapi  ： 代理到服务mockoon服务中
     * local   ： 代理到本地mock
     * dev     :  代理到后端开发
     * ... 这些前缀是可以自定义的，直接在接口配置的第三个参数配置即可
     */
    proxy: {
      // --------------------------- 公共类的配置 -------------------------------------
      /**
       * @description 针对yapi服务的配置，接口有前缀“mocksign” 会代理到该服务
       */
      '/api/mocksign/': {
        target: 'http://60.190.234.60:10064/mock/123',
        pathRewrite: { '^/api/mocksign': '' },
        secure: false,
        changeOrigin: true,
        onProxyRes: function (proxyRes, req, res) {
          proxyRes.headers['fe-hasproxy'] = 'mocksign'
        }
      },
      /**
       * @description 针对mockoon服务的配置，接口有前缀“anyapi” 会代理到该服务
       */
      '/api/anyapi/': {
        target: 'http://localhost:3077',
        pathRewrite: { '^/api/anyapi': '' },
        secure: false,
        changeOrigin: true,
        onProxyRes: function (proxyRes, req, res) {
          proxyRes.headers['fe-hasproxy'] = 'mockoon'
        }
      },
      /**
       * @description 针对后端开发服务的配置，接口有前缀“dev” 会代理到该服务
       */
      '/api/dev/': {
        target: 'http://125.124.197.188:10018/',
        pathRewrite: { '^/api/anyapi': '' },
        secure: false,
        changeOrigin: true,
        onProxyRes: function (proxyRes, req, res) {
          proxyRes.headers['fe-hasproxy'] = 'mockoon'
        }
      },
      /**
       * @description 针对本地mock服务的配置，接口有前缀“local” 会代理到该服务
       * *** 针对一部分接口其实在proxy中已经匹配到了逻辑，但是这个代理服务不可达，
       * 导致异常，这个时候我们希望这种服务可以直接选择mock本地的服务上，这样就可以
       * 达到代理到本地的切换功能 ***
       */
      '/api/local/': {
        target: 'http://localhost:13322',
        pathRewrite: { '^/api/local': '/local' },
        secure: false,
        changeOrigin: true,
        onProxyRes: function (proxyRes, req, res) {
          proxyRes.headers['fe-hasproxy'] = 'mockoon'
        }
      },
      // 针对转发场景的处理
      // '/remote/auth/auth/getArithmeticCode': {
      //   target: 'https://oos-hz.ctyunapi.cn',
      //   pathRewrite: { '^/api/remote/auth/auth/getArithmeticCode': '/damddos/cloud-brain/miniapp/images/verfiy_code.jpeg' },
      //   secure: false,
      //   changeOrigin: true,
      //   onProxyRes: function (proxyRes, req, res) {
      //     console.log(` [ proxy remote ] ${req.url} ------------------------------------`)
      //     proxyRes.headers['fe-hasproxy'] = 'remote'
      //   }
      // },

      // --------------------------- 业务类的配置 -------------------------------------
      '/api/admin/': {
        target: defaultSettings.proxyHost,
        pathRewrite: { '^/api': '' },
        secure: false,
        changeOrigin: true,
        // pathRewrite: { '^/api': '' },
        onProxyReq: function (proxyReq, req, res) {
          // proxyReq.setHeader('fe-hasproxy', 'admin')
        },
        onProxyRes: function (proxyRes, req, res) {
          console.log(
            ` [ proxy admin ] ${req.url} ------------------------------------`
          )
          proxyRes.headers['fe-hasproxy'] = 'admin'
        }
      },
      '/api/platformapi/': {
        target: defaultSettings.proxyHost,
        pathRewrite: { '^/api': '' },
        onProxyReq: function (proxyReq, req, res) {
          // proxyReq.setHeader('fe-hasproxy', 'auth')
        },
        onProxyRes: function (proxyRes, req, res) {
          console.log(
            ` [ proxy auth ] ${req.url} ------------------------------------`
          )
          proxyRes.headers['fe-hasproxy'] = 'auth'
        }
      },
      '/api/api': {
        target: defaultSettings.proxyHost,
        pathRewrite: { '^/api': 'admin' },
        onProxyReq: function (proxyReq, req, res) { },
        onProxyRes: function (proxyRes, req, res) {
          proxyRes.headers['fe-hasproxy'] = 'admin'
        }
      },
      '/api/data-security': {
        target: defaultSettings.proxyHost,
        pathRewrite: { '^/api': '' },
        secure: false,
        changeOrigin: true,
        onProxyReq: function (proxyReq, req, res) { },
        onProxyRes: function (proxyRes, req, res) {
          proxyRes.headers['fe-hasproxy'] = 'admin'
        }
      }
    }
    /**
     * @description 开启本地mock服务
     * ***
     * 默认先去mock中找对应的接口，找不到的话开始匹配上面的代理，
     * 但是实际源码实现逻辑恰好相反，就是我们优先是在上面的proxy中匹配
     * 匹配不到之后才会到下面的mock中去找接口匹配。所以前面加了一个公共代理local@line101
     * ***
     **/
    // before: mock
  },
  configureWebpack: {
    devtool: process.env.NODE_ENV === 'development' ? 'source-map' : undefined,
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      extensions: ['.js', '.json', '.vue'],
      alias: {
        '@': resolve('src'),
        component: resolve('src/components'),
        public: resolve('public')
      }
    },
    // externals: {
    //     vue: 'Vue',
    //     'sec-ui': 'ELEMENT'
    // },
    plugins: [
      // new FileListPlugin({
      //   filename: '_filelist.md'
      // })
    ],
    module: {
      // rules: [{
      //   test: /\.vue$/, use: [
      //     {
      //       loader: path.resolve('./src/redevelop/loader.js'),
      //       options: {/* ... */ }
      //     }
      //   ]
      // }]
    }
  },
  chainWebpack(config) {
    // it can improve the speed of the first screen, it is recommended to turn on preload
    // it can improve the speed of the first screen, it is recommended to turn on preload
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])
    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete('prefetch')

    // set svg-sprite-loader
    config.module.rule('svg').exclude.add(resolve('src/icons')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config.when(process.env.NODE_ENV !== 'development', (config) => {
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/
          }
        ])
        .end()
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // only package third parties that are initially dependent
          },
          elementUI: {
            name: 'chunk-elementUI', // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      })
      // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
      // eslint-disable-next-line no-sequences
      config.optimization.runtimeChunk('single'),
        config.optimization.minimizer('terser').tap((args) => {
          args[0].terserOptions.compress.drop_console = true
          args[0].terserOptions.compress.drop_debugger = true
          args[0].terserOptions.compress.pure_funcs = ['console.log']
          args[0].terserOptions.output = {
            comments: false
          }
          return args
        })

      if (process.env.use_analyzer) {
        config
          .plugin('webpack-bundle-analyzer')
          .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
      }
    })
  }
}
